<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 文章头部信息 -->
    <div class="mb-8">
      <div class="flex items-center space-x-4 text-sm text-gray-500 mb-4">
        <span>{{ article?.categoryName }}</span>
        <span>·</span>
        <span>{{ formatDate(article?.createTime) }}</span>
      </div>

      <h1 class="text-4xl font-bold text-gray-900 mb-6">
        {{ article?.title }}
      </h1>

      <div class="flex items-center space-x-4 mb-8">
        <div class="flex items-center">
          <div
            class="w-12 h-12 bg-gray-200 rounded-full flex items-center justify-center"
          >
            <span class="text-xl">{{ article?.title?.charAt(0) }}</span>
          </div>
          <div class="ml-3">
            <p class="text-gray-900 font-medium">{{ article?.categoryName }}</p>
            <p class="text-sm text-gray-500">
              {{ formatDate(article?.updateTime) }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改为两栏布局 -->
    <div class="grid grid-cols-1 lg:grid-cols-10 gap-8">
      <!-- 左侧主要内容区域 -->
      <div class="lg:col-span-7">
        <!-- 文章封面图 -->
        <div class="mb-8">
          <LazyImage
            :src="article?.thumbnail"
            :alt="article?.title"
            image-class="h-[400px] rounded-lg"
            skeleton-class="h-[400px] rounded-lg"
          />
        </div>

        <!-- 文章内容 -->
        <div class="prose prose-lg max-w-none">
          {{ article?.content }}
        </div>

        <!-- 文章标签 -->
        <div class="mt-8 flex flex-wrap gap-2">
          <span
            v-for="(tag, index) in article?.tagNames"
            :key="index"
            class="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm"
          >
            {{ tag }}
          </span>
        </div>

        <!-- 评论区域 -->
        <div class="mt-16">
          <h2 class="text-2xl font-bold mb-6">评论区</h2>
          <!-- 评论输入框 -->
          <div class="mb-8">
            <textarea
              v-model="commentContent"
              rows="4"
              class="w-full p-4 border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
              placeholder="写下你的评论..."
            ></textarea>
            <div class="mt-2 flex justify-end">
              <button
                @click="submitComment"
                class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90"
              >
                发表评论
              </button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="space-y-6">
            <div
              v-for="comment in comments"
              :key="comment.id"
              class="flex gap-4 p-4 bg-gray-50 rounded-lg"
            >
              <div
                class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center flex-shrink-0"
              >
                <span class="text-lg">{{ comment.userName?.charAt(0) }}</span>
              </div>
              <div class="flex-1">
                <div class="flex items-center justify-between mb-2">
                  <span class="font-medium">{{ comment.userName }}</span>
                  <span class="text-sm text-gray-500">{{
                    formatDate(comment.createTime)
                  }}</span>
                </div>
                <p class="text-gray-700">{{ comment.content }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧相关文章 -->
      <div class="lg:col-span-3">
        <div class="sticky top-4">
          <h2 class="text-xl font-bold mb-6">相关文章</h2>
          <div class="space-y-6">
            <div
              v-for="item in relatedArticles"
              :key="item.id"
              class="group cursor-pointer"
              @click="handleArticleClick(item)"
            >
              <div class="relative overflow-hidden rounded-lg mb-3">
                <!-- <img
                  :src="item.thumbnail"
                  :alt="item.title"
                  class="w-full h-40 object-cover transition-transform duration-300 group-hover:scale-105"
                /> -->
                <LazyImage
                  :src="item.thumbnail"
                  :alt="item.title"
                  image-class="w-full h-40 object-cover transition-transform duration-300 group-hover:scale-105"
                  skeleton-class=" h-40  rounded-lg"
                />
              </div>
              <h3
                class="text-base font-semibold group-hover:text-primary transition-colors line-clamp-2"
              >
                {{ item.title }}
              </h3>
              <p class="text-sm text-gray-500 mt-2">
                {{ formatDate(item.createTime) }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <Toaster />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getArticleById, getArticleList } from '@/api/modules/content'
import { type Content } from '@/api/interface/index'
import { getCommentList, addComment } from '@/api/modules/content'
import { useToast, Toaster } from '@/components/ui/toast'
import LazyImage from '@/components/LazyImage/LazyImage.vue'

const { toast } = useToast()
const route = useRoute()
const router = useRouter()
const id = route.params.id as string
const article = ref<Content.ResArticle>()
const relatedArticles = ref<Content.ResArticle[]>([])

// 获取相关文章
async function getRelatedArticles() {
  if (!article.value?.categoryId) return

  try {
    const params = {
      categoryId: article.value.categoryId,
      pageNum: 1,
      pageSize: 3,
      excludeId: id, // 排除当前文章
    }
    const res = await getArticleList(params)
    relatedArticles.value = res.data.list
  } catch (error) {
    console.error('获取相关文章失败:', error)
  }
}

function handleArticleClick(item: Content.ResArticle) {
  // 跳转到新文章详情
  router.push({
    name: 'detail',
    params: { id: item.id },
  })
}

const commentContent = ref('')
const comments = ref<Content.ResComment[]>([])

// 获取评论列表
async function getComments() {
  try {
    const params = {
      articleId: id,
      pageNum: 1,
      pageSize: 20,
    }
    const res = await getCommentList(params)
    comments.value = res.data
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

// 提交评论
async function submitComment() {
  if (!commentContent.value.trim()) {
    toast({
      title: '提示',
      description: '评论内容不能为空',
      variant: 'destructive',
    })
    return
  }

  try {
    await addComment({
      articleId: id,
      content: commentContent.value,
    })
    toast({
      title: '成功',
      description: '评论发表成功',
    })
    commentContent.value = ''
    await getComments()
  } catch (error) {
    toast({
      title: '错误',
      description: '评论发表失败',
      variant: 'destructive',
    })
  }
}

async function init() {
  try {
    const res = await getArticleById({ id })
    article.value = res.data
    await Promise.all([getRelatedArticles(), getComments()])
  } catch (error) {
    console.error('获取文章详情失败:', error)
  }
}

const formatDate = (dateStr?: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

onMounted(() => {
  init()
})
</script>

<style>
.prose {
  @apply text-gray-700;
}

.prose p {
  @apply mb-4;
}
</style>
